package com.example.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.blog.mapper.HomeWorkMapper;
import com.example.blog.pojo.HomeWork;
import com.example.blog.pojo.Result;
import com.example.blog.service.HomeWorkService;
import com.example.blog.util.TokenUtil.decryptToken;
import com.example.blog.util.TokenUtil.spiltUtils;
import com.example.blog.util.UserUtils.UserUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class HomeWorkServiceImpl extends ServiceImpl<HomeWorkMapper, HomeWork> implements HomeWorkService {

    @Resource
    private UserUtils userIdUtil;
    @Resource
    private HomeWorkMapper homeWorkMapper;
    @Override
    public Result<T> savaHomeWork(HomeWork homeWork, String subject, String token) {
        String pe = decryptToken.decrypt(token);
        String userName = spiltUtils.getUserName(pe);
        Integer userId = userIdUtil.getUserId(userName);
        String nickname = userIdUtil.getNickname(userName);
        String headerUrl = userIdUtil.getHeaderUrl(userName);
        if (nickname!=null){
            homeWork.setUserId(userId);
            homeWork.setNickname(nickname);
            homeWork.setSubject(subject);
            homeWork.setHeaderUrl(headerUrl);
            homeWork.setCreateTime(new Date());
            int insert = homeWorkMapper.insert(homeWork);
            if (insert>0){
                return Result.success("发布成功！");
            }
            return Result.failed("发布失败！");
        }
        return Result.failed("请登陆后才可以发布！");
    }

    @Override
    public Result<List<HomeWork>> getSubject(String Subject,String token) {
        String pe = decryptToken.decrypt(token);
        String userName = spiltUtils.getUserName(pe);
        int identity = userIdUtil.getIdentity(userName);
        if (identity==0){
            QueryWrapper<HomeWork> queryWrapper=new QueryWrapper<>();
            QueryWrapper<HomeWork> h = queryWrapper.eq("subject", Subject);
            List<HomeWork> homeWork = homeWorkMapper.selectList(h);
            return Result.success(homeWork);
        }
        return Result.failed("你的身份无法查看！");
    }

    @Override
    public Result<HomeWork> getHomeWorkById(int id) {
        QueryWrapper<HomeWork> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("id",id);
        HomeWork homeWork = homeWorkMapper.selectOne(queryWrapper);
        return Result.success(homeWork);
    }
}
